﻿<template>
  <div v-if = 'showPopDialog' v-loading = 'loading' element-loading-text = '数据加载中...'>
    <div class = 'page_tableContent'>
       <!-- 检索部分 -->
      <div class = 'page_searchContent'>
        <el-form>
          <el-row :gutter = '10'>
            <el-col :span = '18'>
              <el-form-item>
                <el-input placeholder = "请输入检索内容" v-model = 'popSearchKey' clearable></el-input>
              </el-form-item>
            </el-col>
            <el-col :span = '6'>
              <el-button @click = 'getPopData_dynamic' type = 'primary'>查询</el-button>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <!-- pop多选表格 -->
      <el-table :data = 'table.tableData' style='width:100%' stripe border max-height = '450' min-height = '180' :row-key = 'getRowKeys'
      @select = 'handleSelect' @select-all = 'handleSelectAll'
      ref = 'multipleTablePop' v-if = "uiType === 'MultiPop'">
        <el-table-column type = "selection" width=  "55" align = "center" :reserve-selection = "true"></el-table-column>
        <el-table-column align = 'center' v-for = '(PopItem, popIndex) in table.tableColumn' show-overflow-tooltip
        :key = 'PopItem.text + popIndex' :label = 'PopItem.text'>
          <template slot-scope = 'scope'>
            <span>{{scope.row[PopItem.tableIndex]}}</span>
          </template>
        </el-table-column>
      </el-table>
      <!-- pop单选表 -->
      <el-table :data = 'table.tableData' style='width:100%' stripe border max-height = '450' min-height = '180' v-else-if = "uiType === 'Pop'">
        <el-table-column align = 'center' v-for = '(PopItem, popIndex) in table.tableColumn'  show-overflow-tooltip
        :key = 'PopItem.text + popIndex' :label = 'PopItem.text'>
          <template slot-scope = 'scope'>
            <el-radio  @click.native.prevent = "clickItemText(scope.row[PopItem.tableIndex])"
            v-if = "PopItem.tableIndex === valueKey" :label = 'scope.row[PopItem.tableIndex]' v-model = 'currentValue'></el-radio>
            <span v-else>{{scope.row[PopItem.tableIndex]}}</span>
          </template>
         </el-table-column>
      </el-table>
      <!-- 底部的分页功能 -->
      <el-pagination background v-if = 'totalLength > 10' style = 'margin-top:10px;margin-bottom:-15px;'
      @size-change = "handleSizeChange" @current-change = "handleCurrentChange"
      :current-page.sync = "currentPage" :page-size = 'pageSize'
      :page-sizes = "[10, 25, 50, 100]" layout = "total, sizes, prev, pager, next" :total = 'totalLength'>
      </el-pagination>
    </div>
  </div>
</template>

<script>
import {
  commonUse_changeInherentEventParams
} from '@/components/commonUse.js'
export default {
  props: {
    disabled: {
      type: Boolean,
      default: false
    },
    // 当前组件
    editElementObj: {
      type: Object
    },
    // 值的集合
    currentPageModelsObj: {
      type: Object
    },
    // 当前值
    defaultValue: {
      type: [Array, String, Number]
    },
    // 初始化的状态
    showPopDialog: {
      type: Boolean
    },
    // 调用弹窗的页面
    from: {
      type: String
    }
  },
  data () {
    return {
      currentValue: null,
      loading: false,
      table: {
        tableData: [],
        tableColumn: []
      },
      valueKey: '',
      uiType: '',
      // 页码相关
      totalLength: 0,
      currentPage: 1,
      pageSize: 10,
      // 检索
      popSearchKey: ''
    }
  },
  created () {
    this.init_page()
  },
  watch: {
    showPopDialog: {
      deep: true,
      handler (val) {
        if (val) {
          this.init_page()
        }
      }
    }
  },
  methods: {
    // 初始化页面的方法
    init_page () {
      this.table.tableColumn = []
      this.totalLength = 0
      this.currentPage = 1
      this.pageSize = 10
      this.valueKey = ''
      this.uiType = this.from === 'dynamic' ? this.editElementObj.type : this.editElementObj.item.ui_type
      // 将传递过来的默认值赋值到currentVal
      if (this.uiType === 'Pop') {
        this.currentValue = this.defaultValue || ''
      } else if (this.uiType === 'MultiPop') {
        this.currentValue = (this.defaultValue && this.defaultValue.length) ? JSON.parse(JSON.stringify(this.defaultValue)) : ''
      }
      if (this.from === 'dynamic') {
        // 动态表单调用本弹窗时
        if (this.editElementObj && !this.$isEmptyObject(this.editElementObj) && !this.editElementObj.metauid) {
          this.$message({
            message: '该元素还没有指定元数据表，请在元数据页面管理中进行设置',
            type: 'warning'
          })
          return
        }
        // 获取下拉框的数据
        this.getPopData_dynamic()
      } else if (this.from === 'meta') {
        // 元数据调用本弹窗时
        // 获取下拉框的数据
        this.getPopData_meta()
      }
    },
    // 获取下拉框的数据_动态表单
    getPopData_dynamic () {
      this.loading = true
      this.table.tableData = []
      this.$patch('/md_form/pop/' + this.editElementObj.metauid + '/' + this.editElementObj.model, {
        is_filter_deleted: Object.keys(this.editElementObj.options).indexOf('isFilterDeleted') !== -1 ? this.editElementObj.options.isFilterDeleted : true,
        fixed_orderby_express: Object.keys(this.editElementObj.options).indexOf('fixedOrderbyExpress') !== -1 ? this.getRequestDataOfGetTableDataMethod(this.editElementObj.options.fixedOrderbyExpress) : '',
        this_data: (this.currentPageModelsObj && !this.$isEmptyObject(this.currentPageModelsObj)) ? btoa(encodeURIComponent(JSON.stringify(this.currentPageModelsObj))) : '',
        ref_data: Object.keys(this.$route.query).indexOf('clickRow') !== -1 ? btoa(encodeURIComponent(this.$route.query.clickRow)) : '',
        limit: this.pageSize,
        page: this.currentPage,
        filter: this.popSearchKey
      }).then(data => {
        let dataInfo = data.data.result
        if (dataInfo.code === 'failed') {
          this.$message({
            message: dataInfo.msg,
            type: 'error'
          })
        } else if (dataInfo.code === 'success') {
          this.getTableData(dataInfo)
          this.loading = false
        }
      }).catch(error => {
        console.log(error)
      })
    },
    // 获取下拉框的数据_元数据
    getPopData_meta () {
      this.loading = true
      this.table.tableData = []
      this.$patch('/metadataset/pop/' + this.editElementObj.funUid + '/' + this.editElementObj.item.indexName, {
        is_filter_deleted: Object.keys(this.editElementObj.options).indexOf('isFilterDeleted') !== -1 ? this.editElementObj.options.isFilterDeleted : true,
        fixed_orderby_express: Object.keys(this.editElementObj.options).indexOf('fixedOrderbyExpress') !== -1 ? this.getRequestDataOfGetTableDataMethod(this.editElementObj.options.fixedOrderbyExpress) : '',
        this_data: (this.currentPageModelsObj && !this.$isEmptyObject(this.currentPageModelsObj)) ? btoa(encodeURIComponent(JSON.stringify(this.currentPageModelsObj))) : '',
        limit: this.pageSize,
        page: this.currentPage
      }).then(data => {
        let dataInfo = data.data.result
        if (dataInfo.code === 'failed') {
          this.$message({
            message: dataInfo.msg,
            type: 'error'
          })
        } else if (dataInfo.code === 'success') {
          this.getTableData(dataInfo)
          this.loading = false
        }
      }).catch(error => {
        console.log(error)
      })
    },
    // 获取查询事件的特有的请求参数
    getRequestDataOfGetTableDataMethod (express) {
      let rowObj = (this.currentPageModelsObj && !this.$isEmptyObject(this.currentPageModelsObj)) ? JSON.parse(JSON.stringify(this.currentPageModelsObj)) : null
      let modelsObj = (this.currentPageModelsObj && !this.$isEmptyObject(this.currentPageModelsObj)) ? JSON.parse(JSON.stringify(this.currentPageModelsObj)) : null
      let fixedValue = {
        formKey: '',
        limit: 10,
        page: 1
      }
      return commonUse_changeInherentEventParams(express, rowObj, modelsObj, fixedValue)
    },
    // 初始化表格的数据
    getTableData (dataInfo) {
      this.valueKey = dataInfo.column_value
      this.totalLength = dataInfo.total_count
      // 生成表头
      this.table.tableColumn = []
      if (dataInfo.column_show.length) {
        dataInfo.column_show.forEach((val, index) => {
          let objExam = {}
          if (val.column_desc) {
            objExam = {
              text: val.column_desc,
              tableIndex: val.column_name
            }
          } else {
            objExam = {
              text: val.column_name,
              tableIndex: val.column_name
            }
          }
          this.table.tableColumn.push(objExam)
        })
        let keyColumn = {
          text: this.valueKey,
          tableIndex: this.valueKey
        }
        this.table.tableColumn.unshift(keyColumn)
      }
      // 生成表格的内容
      if (dataInfo.data.length) {
        if (this.uiType === 'MultiPop') {
          // 清空多选表格的已选项
          this.$refs.multipleTablePop.clearSelection()
        }
        dataInfo.data.forEach((val, index) => {
          if (this.uiType === 'MultiPop') {
            // 勾选默认选择的选项
            this.checkedDefaultRow(val, true)
          }
          this.$set(this.table.tableData, index, val)
        })
      }
    },
    // 用户手动选择时
    handleSelect (selection, row) {
      let hadSelected = false
      for (let i = 0; i < selection.length; i++) {
        if (selection[i][this.valueKey] === row[this.valueKey]) {
          hadSelected = true
        }
        this.getSelectedVal(selection[i][this.valueKey], true)
      }
      // 当为取消当前行的选中状态时
      if (!hadSelected) {
        this.getSelectedVal(row[this.valueKey], false)
      }
    },
    // 用户全选时
    handleSelectAll (selectAll) {
      if (selectAll && selectAll.length) {
        // 选中时
        selectAll.forEach(item => {
          this.getSelectedVal(item[this.valueKey], true)
        })
      } else {
        // 取消全选时
        if (this.table.tableData && this.table.tableData.length) {
          this.table.tableData.forEach(item => {
            this.getSelectedVal(item[this.valueKey], false)
          })
        }
      }
    },
    // 获取选中的值
    getSelectedVal (key, selected) {
      // 需要先判断是否已有选择的数据
      if (this.currentValue && this.currentValue.length) {
        let hadPushCurrentVal = false
        for (let i = 0; i < this.currentValue.length; i++) {
          if (key === this.currentValue[i]) {
            hadPushCurrentVal = true
            if (!selected) {
              // 如果不是选中就移除
              this.currentValue.splice(i, 1)
            }
            break
          }
        }
        // 如果是选中,并且没有被添加到已选择的数据列表时就添加
        if (selected && !hadPushCurrentVal) {
          this.$set(this.currentValue, this.currentValue.length, key)
        }
      } else {
        if (selected) {
          // 需要加入选中的行时
          this.currentValue = []
          this.currentValue.push(key)
        } else {
          this.currentValue = null
        }
      }
    },
    // 勾选默认选择的选项
    checkedDefaultRow (row, checkStatus) {
      for (let i = 0; i < this.currentValue.length; i++) {
        if (row[this.valueKey] === this.currentValue[i]) {
          this.$refs.multipleTablePop.toggleRowSelection(row, checkStatus)
          break
        }
      }
    },
    // 表格多选时,设置key
    getRowKeys (row) {
      return row[this.valueKey]
    },
    // 获取选中的值,并且传递到父组件
    getPopValue () {
      if (this.uiType === 'Pop') {
        this.$emit('update:defaultValue', this.currentValue)
      } else if (this.uiType === 'MultiPop') {
        let val = (this.currentValue && this.currentValue.length) ? JSON.parse(JSON.stringify(this.currentValue)) : null
        this.$emit('update:defaultValue', val)
      }
    },
    // 点击单选框按钮时
    clickItemText (e) {
      this.currentValue === e ? this.currentValue = '' : this.currentValue = e
    },
    // 底部页码的部分
    handleSizeChange (val) {
      this.pageSize = val
      if (this.from === 'dynamic') {
        // 动态表单调用本弹窗时
        this.getPopData_dynamic()
      } else if (this.from === 'meta') {
        // 元数据调用本弹窗时
        this.getPopData_meta()
      }
    },
    handleCurrentChange (val) {
      this.currentPage = val
      if (this.from === 'dynamic') {
        // 动态表单调用本弹窗时
        this.getPopData_dynamic()
      } else if (this.from === 'meta') {
        // 元数据调用本弹窗时
        this.getPopData_meta()
      }
    }
  }
}
</script>
